package com.zhuxulin.java.mail.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient {
	private static final String HOST = "127.0.0.1";
	private static final String CODEC = "UTF-8";
	private static final int PORT = 8866;
	private static final int CONN_TIME_OUT = 30;

	private IoConnector conn = null;
	private IoSession session = null;
	private WriteFuture writeFuture = null;

	public MinaClient() {
		conn = new NioSocketConnector();
		// 设置链接超时时间
		conn.setConnectTimeoutMillis(CONN_TIME_OUT);
		// 添加过滤器
		conn.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName(CODEC), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS
						.getValue())));
		// 添加业务逻辑处理器类
		conn.setHandler(new ClientHanlder());
		try {
			ConnectFuture future = conn.connect(new InetSocketAddress(HOST, PORT));// 创建连接
			future.awaitUninterruptibly();// 等待连接创建完成
			session = future.getSession();// 获得session
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public IoSession getSession() {
		return session;
	}

	public void closeSession() {
		session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
		conn.dispose();
	}

	public boolean sendMsg(Object message) {
		writeFuture = session.write(message);
		return writeFuture.isWritten();
	}

	public WriteFuture getFuture() {
		return writeFuture;
	}
}
